﻿using System;
using System.Collections.Generic;
using System.Text;
using Silk.NET.OpenGLES;
using TTEngine.Resource;
using TTEngine.TTMath;

namespace TTEngine.Graphics
{
    public class FontTTF : ResourceObj, IFont
    {
        public int FontSize => _font.Size;

        public PackedTextureGroup PackGroup
        {
            get;
            private set;
        }
        ISystemTtfFont _font;

        Dictionary<int, PackedFontCharInfo> mapChar = new Dictionary<int, PackedFontCharInfo>();

        protected override void OnDestory()
        {

        }
        public FontTTF(ResourcePackage package, ISystemTtfFont font, PackedTextureGroup group)
            : base(package)
        {
            this.PackGroup = group;
            this._font = font;
        }
        public bool EnsureTextPacked(string text)
        {
            bool change = false;
          var safetxt=  System.Text.UnicodeEncoding.UTF32.GetBytes(text);
            unsafe
            {
                fixed(byte* ptr = safetxt)
                {
                    for(var i=0;i<safetxt.Length/4;i++)
                    {
                        var safec=((int*)ptr)[i];
                        if (mapChar.ContainsKey(safec))
                            continue;
                        var cinfo = new PackedFontCharInfo();
                        cinfo.fontadv = _font.GetCharWidth(safec);
                        var data = _font.GetCharImage(safec, 0,true);
                        cinfo.elem = PackGroup.AddSpriteInfo(data, SpriteEffect.GrayAsAlpha, Border.One);
                        mapChar[safec] = cinfo;
                        change = true;
                    }
                }
            }

            return change;

        }
        public void ApplyPackedTextureData()
        {
            this.PackGroup.ApplyTextureData();
        }
        public bool TryGetCharInfo(int c, out PackedFontCharInfo value)
        {
            return mapChar.TryGetValue(c, out value);

        }
    }
}
